package edu.chen.util;

import org.junit.Test;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtils {
    private static final int COOKIES_MAXAGE = 24 * 60 * 60;
    private static final String COOKIES_PATH = "/";


    /**
     * 在本地保存一个Cookie
     * @param response
     * @param data
     * @param name
     */
    public void saveCookie(HttpServletResponse response,String name,String data){
        Cookie cookie = new Cookie(name,data);
        cookie.setPath(COOKIES_PATH);
        cookie.setMaxAge(COOKIES_MAXAGE);
        System.out.println("保存到本地");
        response.addCookie(cookie);
    }


    /**
     * 根据名称查询Cookie,不存在则返回null
     * @param name
     * @param request
     * @return
     */
    public Cookie getCookieByName( HttpServletRequest request,String name){
        Cookie[] cookies = request.getCookies();
        System.out.println(cookies.length);
        if(null != cookies && cookies.length > 0){
            for (Cookie cookie:cookies) {
                System.out.println(cookie.getName());
                if(cookie.getName().equals(name))
                    return cookie;
            }
        }
        return null;
    }
}
